package toOffer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author YuanAo
 * @date 2024/9/29 19:51
 * @description 二叉树的中序遍历
 */

/**
 * 题目：给定一个二叉树的根节点 root ，返回 它的 中序 遍历 。
 */
public class No94 {
    public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        TreeNode node1 = new TreeNode(2, node, null);
        TreeNode tree = new TreeNode(1, null, node1);
        List<Integer> list = inorderTraversal(tree);
        for (Integer integer : list) {
            System.out.print(integer + " ");
        }

    }

    /**
     * 中序遍历：左-中-右
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        dfs(root, list);
        return list;
    }

    private static void dfs(TreeNode root, List<Integer> list) {
        if (root != null){
            dfs(root.left, list);
            list.add(root.val);
            dfs(root.right, list);
        }
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
